package com.ruoyi.framework.security.filter;

import cn.hutool.core.lang.Validator;
import com.ruoyi.charge.auth.entity.ApiToken;
import com.ruoyi.charge.auth.enums.ResponseCode;
import com.ruoyi.charge.auth.service.LoginTokenService;
import com.ruoyi.charge.auth.utils.HttpResonseUtils;
import com.ruoyi.charge.auth.utils.ReleaseUrlUtil;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private LoginTokenService loginTokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        String url = request.getRequestURI();
        String token = request.getHeader("token");
        if (!url.contains("charge")) {
            if (!checkNoAuthUrl(url)) {
                LoginUser loginUser = tokenService.getLoginUser(request);
                if (Validator.isNotNull(loginUser) && Validator.isNull(SecurityUtils.getAuthentication())) {
                    tokenService.verifyToken(loginUser);
                    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        } else if (!ReleaseUrlUtil.checkReleaseUrl(url)) {
            if (StringUtils.isNotEmpty(token)) {
                ApiToken apiToken = loginTokenService.getTokenByAccessToken(token);
                if (apiToken == null) {
                    HttpResonseUtils.NoLogin(request, response, "token 失效！", ResponseCode.TOKEN_INVALID);
                    return;
                }
            } else {
                HttpResonseUtils.NoLogin(request, response, "未登录！", ResponseCode.NO_LOGIN);
                return;
            }

        }

        chain.doFilter(request, response);
    }


    /**
     * 校验不需要登录验证的url
     *
     * @param url
     * @return
     */
    private Boolean checkNoAuthUrl(String url) {
//        if (url.contains("goods")) {
//            return true;
//        }
        return false;
    }
}
